package gr.handmademarket.ui.views;

import gr.handmademarket.po.implementations.Product;
import gr.handmademarket.po.implementations.PurchaseItem;
import gr.handmademarket.ui.WebHandMadeSession;
import gr.handmademarket.ui.pages.MyBasketPage;

import java.util.Arrays;
import java.util.List;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.image.NonCachingImage;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.resource.ContextRelativeResource;

/**
 * purchase items list view.
 */
public class PurchaseItemsListView 
extends ListView<PurchaseItem>{

	private static final Integer[] quantities = new Integer[]{1,2,3,4,5};
	
	/**
	 * Creates a new ImagesListView object. 
	 *
	 * @param id
	 * @param list
	 */
	public PurchaseItemsListView(String id, List<PurchaseItem> items) {
		super(id, items);
	}

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("nls")
	@Override
	protected void populateItem(ListItem<PurchaseItem> item) {
		final PurchaseItem purchaseItem = item.getModelObject();
		Product p = purchaseItem.getProduct();
		String path = "/images/products/" + p.getCode() + ".jpg"; 
		ContextRelativeResource resource = new ContextRelativeResource(path);
		NonCachingImage image = new NonCachingImage("img", resource);
		item.add(image);
		item.add(new Label("name",p.getName()));
		item.add(new Label("price",p.getPrice()));
		DropDownChoice<Integer> quantityCombo = 
				new DropDownChoice<Integer>("quantity", new CompoundPropertyModel<Integer>(purchaseItem.getQuantity()), Arrays.asList(quantities));
		item.add(quantityCombo);
		item.add(createRemoveBasketLink(purchaseItem));
	}
	
	/**
	 * @return ajax remove basket link.
	 */
	@SuppressWarnings("nls")
	private AjaxLink<NonCachingImage> createRemoveBasketLink(PurchaseItem item){
		String path = "/images/basket-delete-icon.png";
		final PurchaseItem localItem = item;
		ContextRelativeResource resource = new ContextRelativeResource(path);
		NonCachingImage image = new NonCachingImage("removeImg", resource);
		AjaxLink<NonCachingImage> ajaxLink = new AjaxLink<NonCachingImage>("removeLink", new Model<NonCachingImage>(image)) {
			/**
			 * serialVersionUID
			 */
			private static final long serialVersionUID = 1L;

			@Override
			public void onClick(AjaxRequestTarget target) {
				WebHandMadeSession session = (WebHandMadeSession) WebHandMadeSession.get();
				session.getUserItems().remove(localItem);
				setResponsePage(new MyBasketPage());
			}
		};
		ajaxLink.add(image);
		return ajaxLink;
	}

}
